import apiList from './api.js';
import { BASE_URL, SIGN } from '@/env.js';
import store from '@/common/store/index.js'
import i18n from '@/common/i18n/index.js'

// 组装接口路径
const getApiPath = path => {
	let apiArray = path.split("."),
		api = apiList
	apiArray.forEach(v => {
		api = api[v]
	});
	return api
}

// 发起请求的函数
const request = (path, data, error = true) => {
	if(!BASE_URL) {
		const noDomainMessage = i18n.t('common.network.noDomain')
		uni.showModal({ title: noDomainMessage })
		throw new Error(i18n.t('common.network.domainBlocked'))
	}
	const api = getApiPath(path)
	if(!api) {
		throw new Error(i18n.t('common.network.apiUndefined'))
	}
	const url = BASE_URL + api.url,
		  method = api.method
	// 通过Promise封装请求, 返回异步请求结果
	return new Promise(async (resolve, reject) => {
		uni.request({
			url,
			data,
			method,
			header: {
				'Content-Type': method === 'GET' ? 'application/json' : 'application/x-www-form-urlencoded',
				'Token': store.state.user.token || '',
				'Sign': SIGN || '',
				'Accept-Language': (i18n.getLocale && i18n.getLocale()) || 'zh-CN'
			},
			success: res => {
				if(res.data.code != 1 && res.data.code != 1314 && res.data.code != 401 && error) {
					console.log(url)
					uni.showToast({
						title: res.data.msg || i18n.t('common.network.requestError'),
						icon: 'none',
						mask: true
					})
				}
				if(res.data.code === 401) {
					store.dispatch('user/logout')
					
					uni.showModal({
						title: i18n.t('common.network.systemTitle'),
						content: i18n.t('common.network.loginRequired'),
						success: res => {
							if(res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
						}
					})
				}
				resolve(res.data)
			},
			fail: err => {
				uni.showToast({
					title: i18n.t('common.network.serverBusy', { url: BASE_URL }),
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}

export default request